/*
 * @Author: your name
 * @Date: 2021-05-28 16:16:56
 * @LastEditTime: 2021-05-31 14:48:16
 * @LastEditors: Please set LastEditors
 * @Description: 测试
 * @FilePath: \egg-demo\app\model\merchant.js
 */

 'use strict';

const merchant = require('../schema/merchant');

 module.exports = app => {
   const { Sequelize, model } = app;
   const { Op } = Sequelize;
   const merchantSchema = require('../schema/merchant')(app);   // 获取表结构
   const Merchant = model.define('merchant', merchantSchema);   // 定义表

   /* 新增 */
   Merchant.saveNew = async merchant => {
     const res = await Merchant.create(merchant);
     return res.uuid;
   };

   /* 修改商家 */
   Merchant.saveModify = async merchant => {
     const { uuid, name, enableStatus, servicePhone, linkPhone, appId, appSecret, mchId,
      mchKey, linkMan, address, version, password, lastModifierId, lastModifierName} = merchant;
     const updateField = {uuid, name, enableStatus, servicePhone, linkPhone, appId, appSecret, mchId,
      mchKey, linkMan, address, version, lastModifierId, lastModifierName, };
     if(password) {
       updateField.password = password;
     }
     const result = await Merchant.update(updateField, { where: { uuid, version }});
     return result;
   };

  /* 修改密码 */
  Merchant.savePasswordModify = async params => {
    const { uuid, oldPasword, password, lastModifierId, lastModifierName } = params;
    const result = await Merchant.update({ password, lastModifierId, lastModifierName }, {
      where: {
        uuid,
        password: oldPasword,
      },
    });

    return result;
  };

  /* 查询商家分页列表 */
  Merchant.query = async ( { attributes, pagenition = {}, filter = {}, sort = [] }) => {
    const { page, pageSize: limit } = pagenition; // 解构并重命名变量
    const { keywordsLike, status } = filter;
    const condition = {
      offset: (page -1 ) * limit,
      limit,
      attributes,
      where: {}
    }
    if(status) {
      condition.where.enableStatus = status;
    }
    if(keywordsLike) {
      condition.where[Op.or] = [
        { userName: { [Op.like]: `%%${keywordsLike}%%` } },
        { name: { [Op.like]: `%%${keywordsLike}%%` } },
        { linkMan: { [Op.like]: `%%${keywordsLike}%%` } },
        { linkPhone: { [Op.like]: `%%${keywordsLike}%%` } },
        { servicePhone: { [Op.like]: `%%${keywordsLike}%%` } },
      ];
    }

    const { count, rows } = await Merchant.findAndCountAll(condition);
    return { page, count, rows };
  };

  Merchant.get = async ({uuid, attributes }) => {
    return await Merchant.findByPk(uuid, {
      attributes,
    });
  }

  return Merchant;

 }
